#include "JavaCaller.h"

//native层回调java方法的工具类
JavaCaller::JavaCaller() {
    //获取Java对象中的回调方法
    jclass clazz = JNI::env->GetObjectClass(JNI::interface);
    onErrorMethod = JNI::env->GetMethodID(clazz, "onError", "(ILjava/lang/String;)V");
}

//JNI接口对象释放，JavaCaller析构
JavaCaller::~JavaCaller() {
    JNI::env->DeleteGlobalRef(JNI::interface);
    JNI::jvm = nullptr;
    JNI::env = nullptr;
    JNI::interface = nullptr;
}

//错误回调
void JavaCaller::onError(int code, const char *message) {
    JNIEnv *env = nullptr;
    bool detached = JNI::jvm->GetEnv((void **) &env, JNI_VERSION_1_6) == JNI_EDETACHED;
    if (detached) JNI::jvm->AttachCurrentThread(&env, nullptr);
    jstring string = nullptr;
    JNI::toJString(message, string);
    env->CallVoidMethod(JNI::interface, onErrorMethod, code, string);
    env->DeleteGlobalRef(string);
    string = nullptr;
    if (detached) JNI::jvm->DetachCurrentThread();
}
